package com.lepinwenhua.independent_edit_text;

import android.content.Context;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

/**
 * @author: 魏从响
 * @date: 2025/10/9
 */
public class IndependentEditTextUtil {

    private final Context context;
    private IndependentEditText[] etCodes = new IndependentEditText[6];
    private int resendTime = 60;
    private CountDownTimer countDownTimer;
    private TextView tv_time;
    private OnEditTextClick onEditTextClick;

    public void resendTime(int resendTime){
        this.resendTime = resendTime;
        startResendTimer();
    }

    public IndependentEditTextUtil(Context context, View v){
        this.context = context;

        initViews(v);
        setupListeners();


    }

    private void initViews(View v) {
        etCodes[0] = v.findViewById(R.id.et_code1);
        etCodes[1] = v.findViewById(R.id.et_code2);
        etCodes[2] = v.findViewById(R.id.et_code3);
        etCodes[3] = v.findViewById(R.id.et_code4);
        etCodes[4] = v.findViewById(R.id.et_code5);
        etCodes[5] = v.findViewById(R.id.et_code6);
        //倒计时
        tv_time = v.findViewById(R.id.tv_time);

        for (int i = 0; i < etCodes.length; i++) {
            if (i!=0){
                etCodes[i].setFocusable(false);
            }
        }

        //自动聚焦首项
        etCodes[0].postDelayed(() -> {
            etCodes[0].requestFocus();
            showKeyboard(etCodes[0]);
        }, 300);
    }

    private void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager)
                context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }

    private void setupListeners() {
        // 设置粘贴监听器
        for (IndependentEditText et : etCodes) {
            et.setOnPasteListener(this::handlePastedCode);
        }

        // 设置文本变化监听器
        for (int i = 0; i < etCodes.length; i++) {
            final int currentIndex = i;
            final int nextIndex = i < etCodes.length - 1 ? i + 1 : -1;

            etCodes[i].addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() == 1 && nextIndex != -1) {
                        etCodes[currentIndex + 1].setFocusableInTouchMode(true);
                        etCodes[currentIndex].setFocusable(false);
                        etCodes[nextIndex].requestFocus();
                    }
                    checkInputComplete();
                }
            });

            // 设置删除键监听
            etCodes[i].setOnKeyListener((v, keyCode, event) -> {
                if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (etCodes[currentIndex].getText().length() == 0 && currentIndex > 0) {
                        etCodes[currentIndex - 1].setFocusableInTouchMode(true);
                        etCodes[currentIndex].setFocusable(false);
                        etCodes[currentIndex - 1].requestFocus();
                        etCodes[currentIndex - 1].setText("");
                        return true;
                    }
                }
                return false;
            });
        }

        // 重新发送验证码点击事件
        if (tv_time!=null){
            tv_time.setOnClickListener(v -> {
                if (resendTime <= 0) {
                    // 这里应该是重新发送验证码的逻辑
                    resendTime = 60;
                    if (onEditTextClick!=null){
                        onEditTextClick.onResendTimeClick();
                    }
                }
            });
        }
    }

    private void handlePastedCode(String code) {
        if (code.length() == 6) {
            for (int i = 0; i < 6; i++) {
                etCodes[i].setText(String.valueOf(code.charAt(i)));
            }
            etCodes[5].setSelection(etCodes[5].length());//光标在末尾
            etCodes[5].requestFocus();
            checkInputComplete();
        }
    }

    private void checkInputComplete() {
        boolean isComplete = true;
        for (IndependentEditText et : etCodes) {
            if (et.getText().length() == 0) {
                isComplete = false;
                break;
            }
        }
        if (isComplete){
            if (onEditTextClick!=null){
                onEditTextClick.onEditTextClick(getInputCode());
            }
        }
    }

    private String getInputCode() {
        StringBuilder code = new StringBuilder();
        for (IndependentEditText et : etCodes) {
            code.append(et.getText().toString());
        }
        return code.toString();
    }

    public void deleteData() {
        for (int i = 0; i < 6; i++) {
            etCodes[i].setText("");
            if (i!=0){
                etCodes[i].setFocusable(false);//失去焦点
            }else {
                etCodes[i].setFocusableInTouchMode(true);//获取焦点
            }
        }
        etCodes[0].requestFocus();
    }

    public void startResendTimer() {
        countDownTimer = new CountDownTimer(resendTime * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                resendTime--;
                tv_time.setText(resendTime + "秒后重新发送");
                tv_time.setTextColor(context.getResources().getColor(android.R.color.darker_gray));
            }

            @Override
            public void onFinish() {
                tv_time.setText("重新发送验证码");
                tv_time.setTextColor(context.getResources().getColor(R.color.color_5ed));
            }
        }.start();
    }


    public void setOnEditTextClick(OnEditTextClick onEditTextClick){
        this.onEditTextClick = onEditTextClick;
    }

    public interface OnEditTextClick{
        void onEditTextClick(String value);
        void onResendTimeClick();
    }

    public void onDestroy() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

}
